package pe.upc.dsd.jjjar.metropolitano;

import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import pe.upc.dsd.jjjar.metropolitano.services.RequestMethod;
import pe.upc.dsd.jjjar.metropolitano.services.RestClient;
import pe.upc.dsd.jjjar.rest.informacion.Bus;
import pe.upc.dsd.jjjar.rest.informacion.Response;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class BusesRequestActivity extends ListActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		RestClient client = new RestClient(
				Constantes.SERVER_ENDPOINT + "/Informacion/rest/info/buses");
		try {
			client.Execute(RequestMethod.GET);
		} catch (Exception e) {
			// textView.setText(e.getMessage());

		}

		String response = client.getResponse();

		Gson gson = new Gson();
		Response responseObject = null;
		
		try{
			responseObject = gson.fromJson(response, Response.class);
		}catch(JsonParseException e){}
		
		if (responseObject != null) {
			final List<Bus> buses = responseObject.getListBuses();
			String[] array = new String[buses.size()];
			for (int i = 0; i < buses.size(); i++) {
				array[i] = buses.get(i).getNombre();
			}

			setListAdapter(new ArrayAdapter<String>(this,
					R.layout.buses_request, array));

			ListView lv = getListView();
			lv.setTextFilterEnabled(true);

			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					String bus = buses.get(position).getCodigo();
					Intent responseIntent = new Intent(
							BusesRequestActivity.this,
							BusesResponseActivity.class);
					responseIntent.putExtra("bus", bus);
					startActivity(responseIntent);

				}
			});

		} else {

			AlertDialog.Builder builder = new AlertDialog.Builder(
					BusesRequestActivity.this);
			builder.setMessage(
					"Se produjo un error en la comunicacion con el WebService.")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									BusesRequestActivity.this.finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();

		}

	}

}
